package com.lun.blog.service.impl;

import com.lun.blog.repostory.TypeRepository;
import com.lun.blog.exceptions.NotFundException;
import com.lun.blog.pojo.Type;
import com.lun.blog.service.TypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.Set;

@Service
public class TypeServiceImpl implements TypeService {

    @Autowired
    private TypeRepository typeRepository;

    @Transactional
    @Override
    public Type getType(Long id) {
        return typeRepository.getOne(id);
    }

    @Override
    @Transactional
    public Type saveType(Type type) {
        return typeRepository.save(type);
    }

    @Override
    @Transactional
    public void updateType(Long id, Type type) {
        Type t = typeRepository.getOne(id);
        if(t==null){
            throw new NotFundException("不存在该类型");
        }
        BeanUtils.copyProperties(type,t);
        typeRepository.save(t);

    }

    @Override
    @Transactional
    public void deleteType(Long id) {
        typeRepository.deleteById(id);
    }

    @Override

    public Page<Type> listPage(Pageable pageable) {
        return typeRepository.findAll(pageable);
    }

    @Override
    public Boolean findByTypeName(String typeName) {
        Type byName = typeRepository.findByName(typeName);
        return (byName==null)?true:false;
    }

    @Override
    public List<Type> findAll() {
        return typeRepository.findAll();
    }

    @Override
    public Type findById(Long typeId) {
        Optional<Type> type = typeRepository.findById(typeId);
        return type.isPresent()?type.get():null;
    }

    @Override
    public List<Type> findByTypeId(Set<Long> typeId) {
        return typeRepository.findByIdIn(typeId);
    }
}
